{% extends "base.html" %} {% block main %}

<script>
    function addToUserList(list, user) {
        var i;
        for (i = 0; i < list.length; i++) {
            if (list[i].id === user.id) {
                return;
            }
        }
        list.push(user);
    }

    function removeFromUserList(list, user) {
        var i, target = -1;
        for (i = 0; i < list.length; i++) {
            if (list[i].id === user.id) {
                target = i;
                break;
            }
        }
        if (target >= 0) {
            list.splice(target, 1);
        }
    }

    function addMessage(list, msg) {
        list.push(msg);
        $('#message-list').parent().animate({
            scrollTop: $('#message-list').height()
        }, 500);
    }

    function debounce(fun, delay) {
        let last, deferTimer;
        return function (args) {
            let that = this;
            let _args = args;
            let now = +new Date();
            if (last && now < last + delay) {
                clearTimeout(deferTimer);
                deferTimer = setTimeout(function () {
                    last = now;
                    fun.apply(that, _args)
                }, delay);
            }else{
                last = now;
                fun.apply(that, _args)
            }
        }
    }

    window.onload = function startWebSocket() {
        var vmMessageList = new Vue({
            el: '#message-list',
            data: {
                messages: []
            }
        });
        var vmUserList = new Vue({
            el: '#user-list',
            data: {
                users: []
            }
        });

        var ws_url = 'ws://' + location.hostname + ':3000/ws/chat';

        console.log(ws_url);

        var ws = new WebSocket(ws_url);

        ws.onopen = function (evt) {
        }

        ws.timer = null;

        ws.onmessage = function (event) {
            var data = event.data;
            var msg = JSON.parse(data);
            if (msg.type === 'list') {
                vmUserList.users = msg.data;
            } else if (msg.type === 'join') {
                addToUserList(vmUserList.users, msg.user);
                debounce(addMessage(vmMessageList.messages, msg), 1000)
            } else if (msg.type === 'left') {
                removeFromUserList(vmUserList.users, msg.user);
                debounce(addMessage(vmMessageList.messages, msg), 1000)
            } else if (msg.type === 'chat') {
                addMessage(vmMessageList.messages, msg);
            }
        };

        ws.onclose = function (evt) {
            console.log('[closed] ' + evt.code);
            var input = $('#form-chat').find('input[type=text]');
            input.attr('placeholder', 'WebSocket disconnected.');
            input.attr('disabled', 'disabled');
            $('#form-chat').find('button').attr('disabled', 'disabled');
        };

        ws.onerror = function (code, msg) {
            console.log('[ERROR] ' + code + ': ' + msg);
        };

        $('#form-chat').submit(function (e) {
            e.preventDefault();
            var input = $(this).find('input[type=text]');
            var text = input.val().trim();
            console.log('[chat] ' + text);
            if (text) {
                input.val('');
                ws.send(text);
            }
        });
    };
</script>

<style>
    .panel-default {
        height: 100%;
        margin-bottom: 10%;
        padding: 5% 5% 0 5%;
        border: 1px solid;
    }

    .panel-chat {
        height: 500px;
        overflow-x: hidden;
        overflow-y: scroll;
    }

    .message-list-item {
        margin-bottom: 25px;
    }

    .media-time {
        float: right;
    }
</style>

<div class="container">
    <div class="row">
        <div class="col-md-8">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">Room</h3>
                </div>
                <div class="panel-body">
                    <div class="panel-chat">
                        <div id="message-list">
                            <div class="message-list-item" v-for="msg in messages">
                                <div v-if="msg.type === 'join'">
                                    <div class="media-body">
                                        <h6 class="media-heading" v-text="msg.data"></h6>
                                    </div>
                                </div>
                                <div v-if="msg.type === 'left'">
                                    <div class="media-body">
                                        <h6 class="media-heading" v-text="msg.data"></h6>
                                    </div>
                                </div>
                                <div v-if="msg.type === 'chat'">
                                    <div class="media">
                                        <div class="media-body">
                                            <h4 class="media-heading" v-text="msg.user.name"></h4>
                                            <span v-text="msg.data"></span>
                                            <span v-text="msg.time" class="media-time"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div>
                        <form id="form-chat" action="#0">
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="Write something?">
                                <span class="input-group-btn"><button class="btn btn-default"
                                        type="submit">Send</button></span>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">Users</h3>
                </div>
                <div class="panel-body">
                    <div>
                        <div id="user-list">
                            <div class="media" v-for="user in users">
                                <div class="media-left">
                                </div>
                                <div class="media-body">
                                    <h4 class="media-heading" v-text="user.name + ' (' + user.id + ')'"></h4>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}